import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Form, Input, Cascader, Button, message, Radio, Checkbox } from 'antd'
import { FileAddOutlined, DeleteFilled } from '@ant-design/icons'
import { textbookOptions } from '../../config/cascaderOptions'
import {createGetProblem} from '../../redux/actions/problem'
import { fmtNumbertoEN, fmtNumbertoType,fmtTypetoNumber } from '../../utils'
import http from '../../api'

class AddProblem extends Component {
    constructor(props){
        super(props)
        this.handleChange.bind(this)
    }
    formRef = React.createRef()
    state = {
        options: [],
        type:''
    }
    handleSubmit = (value) =>{
        let{id} = this.props.match.params
        value.options = this.state.options
        value.type= fmtTypetoNumber(value.type)
        value.answer = typeof value.answer ==='object'?value.answer.join(''):value.answer
        value.grade = value.edition[0]
        value.course = value.edition[1]
        value.publisher = value.edition[2]
        delete(value.edition)
        if (id) {
            value.id = id
            http.editProblem(value).then(res=>{
                if(res.data.status===0){
                    message.success('编辑成功！')
                    this.props.history.replace('/problempool/list')
                }
            })
        }else{
            http.createProblem(value).then(res=>{
                if(res.data.status===0){
                    message.success('创建成功！')
                    this.props.history.replace('/problempool/list')
                }
            })
        }
        // request.createProblem(value)
    }
    handleFail = (e)=>{
        message.warn('请确认内容正确后提交！')
    }
    addOptions = (e)=>{
        let {options} = this.state
        if (options.length < 10) {
            options.push({id:+new Date(),text:''})
            this.setState({options})
        } else{
            message.destroy()
            message.warn('已添加至最大选项个数！')
        }
    }
    deleteOption =(i)=>{
        const {options} = this.state
        if (options.length>1) {
            options.splice(i,1)
        }else{
            message.warn('至少有一个选项！')
        }
        this.setState({options: options})
    }
    handleChange(index,e){
        let {options} = this.state
        options[index].text = e.target.value
        this.setState({
            options
        })
    }
    changeFields = (cField, aFields)=>{
        // console.log(cField);
        // console.log(aFields);
        if(cField.length && cField[0].name[0] === 'type'){
            if (cField[0].value==='single' || cField[0].value==='multiple') {
                this.generateOptions()
            }else {
                this.setState({options:[]})
            }
            this.setState({type:cField[0].value})
        }
    }
    generateOptions=()=>{
        let options = this.props.subject.options || [] 
        let{id} = this.props.match.params
        if (options!==null && !id) {
            for (let i=0;i<4;i++){
                options.push({id:+new Date()+i,text:''})
                // setTimeout(() => {
                //     let index = i
                //     this.setState({
                //         options:this.props.subject.options || [...this.state.options, {id:+new Date()+index,option:''}]
                //     })
                // }, 10);
            }
        }
        this.setState({options: [...options]})
    }
    componentDidMount(){
        const {subject} = this.props
        if(subject.type===0 || subject.type===1) this.generateOptions()
        subject.grade&&this.formRef.current.setFieldsValue({
            title:subject.title,
            edition:subject.grade && [subject.grade,subject.course,subject.publisher],
            type:fmtNumbertoType(subject.type)||'',
            answer:subject.answer[0],
            desc:subject.desc
        })
    }
    componentWillUnmount(){
        this.props.setProblem([])
    }
    render() {
        // console.log(this.props);
        // console.log(this.state);
        return (
            <div style={{width:'100%', height:'100%'}}>
                <Form 
                    ref={this.formRef}
                    layout="horizontal"
                    wrapperCol={{span:16}} 
                    labelCol={{span:4}}
                    onFinish={this.handleSubmit}
                    onFinishFailed={this.handleFail}
                    onFieldsChange={this.changeFields}
                >
                    <Form.Item name="title" label="题目" rules={[{ required: true, message: '请输入题目' }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item name="edition" label="教材版本" rules={[{ required: true, message: '请选择教材版本' }]}>
                        <Cascader options={textbookOptions} />
                    </Form.Item>
                    <Form.Item label="题型" name='type' rules={[{ required: true, message: '请选择题型' }]}>
                        <Radio.Group disabled={this.props.match.params.id}>
                            <Radio value="single">单选题</Radio>
                            <Radio value="multiple">多选题</Radio>
                            <Radio value="judge">判断题</Radio>
                            <Radio value="briefAnswer">简答题</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item label="选项">
                        <Button type="dashed" style={{marginBottom:'5px',display:this.state.options.length<1?'none':''}} onClick={this.addOptions} ><FileAddOutlined />添加选项</Button>
                        {
                            this.state.options.map((item,i)=>{
                                return(
                                    <div key={item.id} style={{position:'relative'}}>
                                        <Input onChange={(e)=>{this.handleChange(i,e)}} value={this.state.options[i].text} style={{marginBottom:'5px',width:'96%'}}  addonBefore={fmtNumbertoEN(i)} />
                                        <DeleteFilled style={{position:'absolute',right:0,top:'10px'}} onClick={()=>this.deleteOption(i)} />
                                    </div>
                                    )
                            })
                        }
                    </Form.Item>
                    <Form.Item label="答案" name="answer" rules={[{ required: true, message: '请输入答案' }]}>
                        {
                            this.state.type==='single'?
                            <Radio.Group>
                                {
                                    this.state.options.map((r,i)=>
                                        <Radio key={r.id} value={fmtNumbertoEN(i)}>{fmtNumbertoEN(i)}</Radio>
                                    )
                                }
                            </Radio.Group>:
                            this.state.type==='multiple'?
                            <Checkbox.Group>
                                {
                                    this.state.options.map((r,i)=>
                                        <Checkbox key={r.id} value={fmtNumbertoEN(i)}>{fmtNumbertoEN(i)}</Checkbox>
                                    )
                                }
                            </Checkbox.Group> :
                            this.state.type==='judge'?
                            <Radio.Group>
                                <Radio value="true">T</Radio>
                                <Radio value="false">F</Radio>
                            </Radio.Group>:
                            this.state.type==='briefAnswer'?
                            <Input.TextArea cols={2} />:<Input.TextArea cols={2} />
                        }
                    </Form.Item>
                    <Form.Item label="解析" name="desc" rules={[{ required: true, message: '请输入解析' }]}>
                        <Input.TextArea rows={4} />
                    </Form.Item>
                    <Form.Item >
                        <Button style={{position:'relative',left:'275px'}} type="primary" htmlType="submit">创建</Button>
                    </Form.Item>
                </Form>
            </div>
        )
    }
}

export default connect(
    state=>({subject:state.problem}),
    {setProblem:createGetProblem}
)(AddProblem)
